package him.works.trainapp;

import him.works.trainapp.Utils.ArgumentsBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class PlaceholderFragment extends Fragment {
	
	private FrontActivity mCurrentActivity;
	
	private static final String TAG = "PlaceholderFragment";
	private static final String CLASS_NAME = PlaceholderFragment.class.getSimpleName();
	
	private String mTrainLine = Utils.EMPTY;
	private String mDirection = Utils.EMPTY;
	private String mFromStn = Utils.EMPTY;
	
	private String[] STATIONS;	
	private String[] LINE;	
	private static final String[] DIRECTION = new String[] {
        "Up", "Down"
    };
	private Map<String, String> mMapDirn = new HashMap<String, String>(); 
	private Map<String, String> mMapLines = null;

	public PlaceholderFragment() {}
	
	@Override
	public void onAttach(Activity activity) {		
		super.onAttach(activity);
		mCurrentActivity = (FrontActivity) activity;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_front,
				container, false);
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mMapLines = Utils.getMapFromProperties(mCurrentActivity, Utils.FILE_LINES);
		LINE = Utils.getArrayOfMapValues(mMapLines);
		mTrainLine = Utils.getKeyOfMapValues(mCurrentActivity, Utils.FILE_LINES, mMapLines, LINE[0]);
		((TimePicker) mCurrentActivity.findViewById(R.id.fromTime)).setOnTimeChangedListener(new TrainTimeListenerImpl());
	}
	
	@Override
	public void onResume() {
		super.onResume();
		setInputData(R.id.spinnerLine);
	}
	
	/**
	 * Sets data in views
	 */
	public void setInputData(int iIdDropdown) {		
		BaseAdapter adapter = null;
		switch(iIdDropdown) {
		case R.id.spinnerFromStn: 
			adapter = new ArrayAdapter<String>(mCurrentActivity,
	                android.R.layout.simple_dropdown_item_1line, STATIONS);
			Spinner spinnerFromStn = (Spinner)
	                mCurrentActivity.findViewById(iIdDropdown);
	        spinnerFromStn.setAdapter(adapter);
	        spinnerFromStn.setOnItemSelectedListener(new SpinnerLstr());
	        break;
		case R.id.spinnerLine:
			adapter = new ArrayAdapter<String>(mCurrentActivity,
	                android.R.layout.simple_dropdown_item_1line, LINE);
			Spinner spinnerTrainLines = (Spinner) mCurrentActivity.findViewById(iIdDropdown);
			spinnerTrainLines.setAdapter(adapter);
			spinnerTrainLines.setOnItemSelectedListener(new LineSpinnerLstr());
			break;
		case R.id.spinnerDirection: 
			mMapDirn.put(STATIONS[0] + " TO " + STATIONS[STATIONS.length - 1], DIRECTION[0]);
			mMapDirn.put(STATIONS[STATIONS.length - 1] + " TO " + STATIONS[0], DIRECTION[1]);
			String []strarDirn = {STATIONS[0] + " TO " + STATIONS[STATIONS.length - 1], 
					STATIONS[STATIONS.length - 1] + " TO " + STATIONS[0]};
			adapter = new ArrayAdapter<String>(mCurrentActivity,
	                android.R.layout.simple_dropdown_item_1line, strarDirn);
			Spinner spinnerDirection = (Spinner) mCurrentActivity.findViewById(iIdDropdown);
			spinnerDirection.setAdapter(adapter);
			spinnerDirection.setOnItemSelectedListener(new SpinnerLstr());
			break;
		}		
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, CLASS_NAME + ":entered onDestroy()");
		mCurrentActivity = null;
		super.onDestroy();
	}


	protected void getStationsData() {
		ArgumentsBean argbeanObj = Utils.getArgumentBean(
				mCurrentActivity.getApplicationContext(), Utils.EMPTY, "Up", mTrainLine,
				0, 0);
		new LinePopulateTask().execute(argbeanObj);
	}
		
	private class SpinnerLstr implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			switch(parent.getId()) {
			case R.id.spinnerDirection: 
				mDirection = mMapDirn.get((String) parent.getItemAtPosition(pos));
				break;
			case R.id.spinnerFromStn:
				mFromStn = (String) parent.getItemAtPosition(pos);
				break;
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {}		
	}
		
	private class LineSpinnerLstr implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
				if(parent.getId() == R.id.spinnerLine) {
					String strValue = (String) parent.getItemAtPosition(pos);
					mTrainLine = Utils.getKeyOfMapValues(mCurrentActivity, Utils.FILE_LINES, mMapLines, strValue);
					getStationsData();					
				}
			}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {}	
	} 
	
	private class LinePopulateTask extends AsyncTask<ArgumentsBean, Void, ArrayList<String>> {

		@Override
		protected ArrayList<String> doInBackground(ArgumentsBean... argbeanObj) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					Looper.prepare();
					Handler handlerProgress = new Handler();
					handlerProgress.post(new Runnable() {
						public void run() {
							mCurrentActivity.mProgress = new ProgressDialog(mCurrentActivity);
							mCurrentActivity.mProgress.setCancelable(true);
							mCurrentActivity.mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
							mCurrentActivity.mProgress.setProgress(0);
							mCurrentActivity.mProgress.setMax(100);
							mCurrentActivity.mProgress.show();
							while (Utils.WORK_PROGRESS < 100) {
								mCurrentActivity.mProgress
										.setProgress(Utils.WORK_PROGRESS);
								try {
									Thread.sleep(1000);
								} catch (InterruptedException e) {}
							}
							mCurrentActivity.mProgress.dismiss();
						}
					});
				}
			}).start();
			ArrayList<String> listStations = Utils.getTrainStations(argbeanObj[0]);
			return listStations;
		}
				
		protected void onPostExecute(ArrayList<String> listResult) {
			STATIONS = (listResult == null) ? null : (new String[listResult.size()]);
			if(listResult.isEmpty()) {
				mCurrentActivity.showNoNetwork();
			} else {
				for(int i=0; i<listResult.size(); i++) {
					STATIONS[i] = listResult.get(i);
					Log.i("BANANA", STATIONS[i]);
				}
				setInputData(R.id.spinnerFromStn);
				setInputData(R.id.spinnerDirection);
			}
		}		
	}
	
	private class TrainTimeListenerImpl implements OnTimeChangedListener {
		
		@Override
		public void onTimeChanged(TimePicker arg0, int arg1, int arg2) {
			int iPickedHour = ((TimePicker) mCurrentActivity.findViewById(R.id.fromTime)).getCurrentHour().intValue();
			int iPickedMinute = ((TimePicker) mCurrentActivity.findViewById(R.id.fromTime)).getCurrentMinute().intValue();
			Log.i("BANANA", "before mCurrentActivity.launchResults.. mFromStn: "+mFromStn+"| mDirection: "+mDirection);
			if(mFromStn==null || mDirection==null || mFromStn.isEmpty() || mDirection.isEmpty()) {
				return;
			}
			mCurrentActivity.launchResults(mFromStn, mTrainLine, mDirection, iPickedHour, iPickedMinute);
		}
		
	}
	
}
